package com.china08.yxyapi.api.manage.stu.mystudy.huixue.scoreimprove;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlan;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnow;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowTrainRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanRepository;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import io.swagger.annotations.ApiOperation;

/**
 * 成绩提升 计划详情
 * 
 */
@CrossOrigin
@RestController
public class HuiXueScoreImproveDetailController extends YxyApiBaseController {

    @Autowired
    private YxyHuixuePlanRepository yxyHuixuePlanRepository;
    @Autowired
    private YxyHuixuePlanKnowRepository yxyHuixuePlanKnowRepository;
    @Autowired
    private YxyHuixuePlanKnowTrainRepository yxyHuixuePlanKnowTrainRepository;
    @Autowired
    private MongoTemplate mTemplate;

    @ResponseBody
    @ApiOperation(value = "成绩提升首页 计划详情")
    @RequestMapping(value = "/api_yw/manage/stu/mystudy/huixue/scoreimprove/plandetail/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel)
            throws ParseException {
        RespModel model = new RespModel();
        YxyHuixuePlan yxyHuixuePlan = yxyHuixuePlanRepository.findById(reqModel.planId);
        if (yxyHuixuePlan != null) {
            model.lastScoreType = yxyHuixuePlan.getLastScoreType(); // 上次考试分值（尺子的总长度）,
                                                                    // 100,120,150,180
            model.expectScore = yxyHuixuePlan.getExpectScore();// 目标提分
            model.lastScore = yxyHuixuePlan.getLastScore();
            model.progress = yxyHuixuePlan.getProgress() == null ? 0d : yxyHuixuePlan.getProgress();// 目标掌握度
            model.chiScore = model.expectScore * model.progress * 0.01 + yxyHuixuePlan.getLastScore(); // 尺子的考试分数(目标提分*目标完成度+初始分数)
            model.mubiaoScore = yxyHuixuePlan.getLastScore() + model.expectScore;// 目标分数
            if (model.mubiaoScore > model.lastScoreType) model.mubiaoScore = yxyHuixuePlan.getLastScoreType() + 0d;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 开始时间
            Integer beginDate = yxyHuixuePlan.getBeginDate();
            String beginDateString = null;
            if (beginDate != null && beginDate != 0) {
                beginDateString = String.valueOf(beginDate);
                beginDateString = beginDateString.substring(0, 4) + "-" + beginDateString.substring(4, 6) + "-"
                        + beginDateString.substring(6);
            }
            // 结束时间
            Integer endDate = yxyHuixuePlan.getEndDate();
            String endDateString = null;
            Date endDate2 = null;
            if (endDate != null && endDate != 0) {
                endDateString = String.valueOf(endDate);
                endDateString = endDateString.substring(0, 4) + "-" + endDateString.substring(4, 6) + "-"
                        + endDateString.substring(6);
                endDate2 = sdf.parse(endDateString);
            }
            model.restime = this.getIntervalDays(sdf.parse(sdf.format(new Date())), endDate2) + 1;// 学习计划剩余时间
            // 已完成计划的知识点数量(去除重复知识点)
            DBCollection collection = mTemplate.getCollection(mTemplate.getCollectionName(YxyHuixuePlanKnow.class));
            DBObject dbObject = new BasicDBObject("plan_id", yxyHuixuePlan.getId());
            dbObject.put("progress", (double) 100);
            @SuppressWarnings("rawtypes")
            List list = collection.distinct("pk_id", dbObject);
            long knowCount = list.size();
            // long knowCount =
            // yxyHuixuePlanKnowRepository.countByPlanIdAndProgress(yxyHuixuePlan.getId(),
            // (double) 100);// 已完成计划的知识点数量
            // model.knowDescription = "本次计划共涉及" + yxyHuixuePlan.getKnowCount()
            // + "个知识点已完成计划的知识点有" + knowCount + "个";
            model.knowtotal = yxyHuixuePlan.getKnowCount();
            model.knowfinish = knowCount;
            model.iconStatus = yxyHuixuePlan.getIconStatus();
            if (yxyHuixuePlan.getProgress() == 100) {
                StringBuffer commentStr = new StringBuffer();
                commentStr.append("在" + yxyHuixuePlan.getSemesterName() + "中的" + yxyHuixuePlan.getBookContentName());
                commentStr.append("将分数从<span style=\"color: red;\">" + yxyHuixuePlan.getLastScore());
                commentStr.append("</span>分提高到<span style=\"color: red;\">");
                commentStr.append((yxyHuixuePlan.getLastScore() + yxyHuixuePlan.getExpectScore()) + "</span>分的计划，");
                commentStr.append("已提前完成！");
                model.comment = commentStr.toString();// 知识点统计下面判断的那句话
            } else {
                model.comment = yxyHuixuePlan.getNotice();// 知识点统计下面判断的那句话
            }
            model.charName = yxyHuixuePlan.getBookContentName();// 学习计划中选择的章
        } else {
            model.lastScore = 0d;
            model.lastScoreType = 0; // 上次考试分值（尺子的总长度）, 100,120,150,180
            model.expectScore = 0;// 目前提分
            model.progress = 0d;// 目标完成度
            model.chiScore = 0d; // 尺子的考试分数(目标提分*目标完成度+初始分数)
            model.mubiaoScore = 0d;// 目标分数
            model.restime = 0;// 学习计划用时
            model.knowtotal = 0;
            model.knowfinish = 0l;
            // model.knowDescription = "本次计划共涉及0个知识点已完成计划的知识点有0个";
            model.iconStatus = 0;// 表情状态标识
            model.comment = "";// 知识点统计下面判断的那句话
            model.charName = "";// 学习计划中选择的章
        }

        List<Object[]> objs = new ArrayList<Object[]>();// 学习计划中章节下面所对应的所有小节及知识点情况
        if (StringUtils.isNotBlank(reqModel.planId)) {
            // 通过计划id查出来总共有多少个知识点
            List<YxyHuixuePlanKnow> yxyHuixuePlanKnowTrainLst = yxyHuixuePlanKnowRepository
                    .findByPlanIdOrderByOrderNumAsc(reqModel.planId);
            if (yxyHuixuePlanKnowTrainLst != null && yxyHuixuePlanKnowTrainLst.size() > 0) {
                // 根据章节名字对知识点集合进行分组
                Map<String, List<YxyHuixuePlanKnow>> groupByYxyHuixuePlanKnowTrain = yxyHuixuePlanKnowTrainLst.stream()
                        .collect(Collectors.groupingBy(YxyHuixuePlanKnow::getBookContentsName));
                // 根据orderNum对分组后的集合进行排序
                Map<String, List<YxyHuixuePlanKnow>> groupByYxyHuixuePlanKnowTrain2 = new LinkedHashMap<>();
                groupByYxyHuixuePlanKnowTrain.entrySet().stream()
                        .sorted(new Comparator<Map.Entry<String, List<YxyHuixuePlanKnow>>>() {
                            @Override
                            public int compare(Entry<String, List<YxyHuixuePlanKnow>> o1,
                                    Entry<String, List<YxyHuixuePlanKnow>> o2) {
                                return o1.getValue().get(0).getOrderNum().compareTo(o2.getValue().get(0).getOrderNum()); // 升序
                            }
                        }).forEachOrdered(e -> groupByYxyHuixuePlanKnowTrain2.put(e.getKey(), e.getValue()));

                Object[] objects2 = null;
                List<CharpterModel> charpterModels = null;
                for (String key : groupByYxyHuixuePlanKnowTrain2.keySet()) {
                    CharpterModel charpterModel = null;
                    charpterModels = new ArrayList<CharpterModel>();
                    objects2 = new Object[2];
                    objects2[0] = key;
                    for (YxyHuixuePlanKnow yxyHuixuePlanKnow : groupByYxyHuixuePlanKnowTrain2.get(key)) {
                        charpterModel = new CharpterModel();
                        charpterModel.knowName = yxyHuixuePlanKnow.getKnowName();
                        charpterModel.attention = yxyHuixuePlanKnow.getAttention();
                        charpterModel.progress = yxyHuixuePlanKnow.getProgress();
                        if (StringUtils.isNotBlank(reqModel.studentId)) {
                            charpterModel.countTrain = yxyHuixuePlanKnowTrainRepository
                                    .countByStudentIdAndPlanIdAndKnowId(reqModel.studentId, reqModel.planId,
                                            yxyHuixuePlanKnow.getKnowId());
                        } else {
                            charpterModel.countTrain = 0l;
                        }
                        charpterModel.id = yxyHuixuePlanKnow.getPkId();
                        charpterModel.knowId = yxyHuixuePlanKnow.getKnowId();
                        charpterModel.studentId = reqModel.studentId;
                        charpterModel.planId = reqModel.planId;
                        charpterModels.add(charpterModel);
                    }
                    objects2[1] = charpterModels;
                    objs.add(objects2);
                }
            }

        }
        model.studObjects = objs;
        return model;

    }

    protected static class RespModel extends YxyApiRespModel {
        // 上次考试分值
        public Integer lastScoreType;// 上次考试成绩分值（尺子的总长度）, 100,120,150,180
        // 初始分数
        public Double lastScore;// 上次考试分数, 小数点后一位
        // 预期提分
        public Integer expectScore;// 预期提高分数, 5, 10, 15, 20
        // 目标分数
        public Double mubiaoScore;
        // 尺子的考试分数(目标提分*目标完成度+初始分数)
        public Double chiScore;
        // 学习计划剩余时间
        public Integer restime;
        // 知识点总数
        public Integer knowtotal;
        // 已完成知识点
        public Long knowfinish;
        // 知识点统计
        // public String knowDescription;
        // 完成度
        public Double progress;
        // 图标状态 1.悲伤 2.微笑 3.惊喜
        public Integer iconStatus;
        // 知识点统计下面判断的那句话
        public String comment;
        // 学习计划中选择的章
        public String charName;
        // 学习计划中章节下面所对应的所有小节及知识点情况
        public List<Object[]> studObjects;
    }

    protected class CharpterModel {
        // 知识点pkid
        public String id;
        // 知识点名称
        public String knowName;
        // 关注等级
        public Integer attention;
        // 知识点完成度
        public Double progress;
        // 训练次数
        public Long countTrain;
        // 知识点id
        public String knowId;
        // studentId
        public String studentId;
        // 计划id
        public String planId;
    }

    protected static class ReqModel extends YxyApiReqModel {
        // 计划id
        public String planId;
        // 学生id
        public String studentId;
    }

    private Integer getIntervalDays(Date fDate, Date oDate) {

        if (null == fDate || null == oDate) {

        return -1;

        }

        long intervalMilli = oDate.getTime() - fDate.getTime();

        return (int) (intervalMilli / (24 * 60 * 60 * 1000));

    }
}
